from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
# from django.http import HttpRequest
from .models import Grades
from .models import Students
from .models import StudentsManager
from django.db.models import F, Q
from django.shortcuts import redirect
# from django.http import HttpResponseRedirect


# 定义了一个视图，也就是一个html页面,这是不用模板
# def index(request):
#     return HttpResponse("sunck is a good man !")
# 定义一个视图，使用模板
def index(request):
    return render(request, "myApp/index.html")


# 支持URL中传参数，这个是一个参数，下面函数是传两个参数
def detail1(request, num):
    return HttpResponse("detail-%s" % num)


def detail2(request, num, num2):
    return HttpResponse("detail-%s-%s" % (num, num2))


# 展示班级列表

def grades(request):
    # 先去模板里取数据
    print("this is myApp/views.py")

    gradesList = Grades.objects.all()
    # 将数据传递给模板，模板再渲染页面，将渲染 好的页面返回给浏览器
    return render(request, "myApp/grades.html", {"grades": gradesList})
    # 参数说明，"myApp/grades.html"是定义好的模板页面，
    # {"grades": gradesList})中的grades是模板中定义的变量，gradesList是视图中的变量


def students(request):
    # 先去模板里取数据
    studentsList = Students.stuObj.all()
    # 将数据传递给模板，模板再渲染页面，将渲染 好的页面返回给浏览器
    return render(request, "myApp/students.html", {"students": studentsList})


def students2(request):
    # 先去模板里取特定的数据
    studentsList = Students.stuObj1.get(sage=20)
    print(type(studentsList))
    # 将数据传递给模板，模板再渲染页面，将渲染好的页面返回给浏览器
    # return render(request, "myApp/students.html", {"students": studentsList})
    return HttpResponse("----------")


# 限制显示前几条数据
def students3(request):
    # 先去模板里取数据
    studentsList = Students.stuObj.all()[0:3]
    return render(request, "myApp/students.html", {"students": studentsList})


# 结合上一个函数，可以实现一个分页功能
def stupage(request, page):
    # 先去模板里取数据
    # 第1页，显示0-5,第2页显示5-10,第3页显示10-15
    page = int(page)
    studentsList = Students.stuObj.all()[page * 5 - 5:page * 5]
    return render(request, "myApp/students.html", {"students": studentsList})
    # return HttpResponse("----------")


def studentSearch(request):
    # 字段查询实例：contain
    # studentList = Students.stuObj1.filter(sname__contains="zhang")
    # 字段查询实例：startswith
    # studentList = Students.stuObj1.filter(sname__startswith="li")
    # 字段查询实例:endswith
    # studentList = Students.stuObj1.filter(sname__endswith="si")
    # 字段查询实例:in
    # studentList = Students.stuObj1.filter(pk__in=[10, 12, 13])
    # 字段查询实例:gt,lt,gte,lte
    # studentList = Students.stuObj1.filter(sage__gte=34)
    # 字段查询实例:exact
    # studentList = Students.stuObj1.filter(sage__exact=34)
    # 字段查询实例:gt,lt,gte,lte
    # studentList = Students.stuObj1.filter(sage__gt=34)
    # 字段查询实例:gt,lt,gte,lte
    # studentList = Students.stuObj1.order_by("sage")
    # 字段查询实例:gt,lt,gte,lte
    studentList = Students.stuObj1.order_by("sage").values()
    return render(request, "myApp/students.html", {"students": studentList})


def gradesStudents(request, num):
    # 按传入的班级id号去取所有学生信息
    grade = Grades.objects.get(pk=num)
    studentsList = grade.students_set.all()
    # 返回给模板
    return render(request, "myApp/students.html", {"students": studentsList})


# F对象的使用示例
def gradesF(request):
    # F对象的使用，拿出女孩人数多于男孩人数的班级
    # gradesList = Grades.objects.filter(ggirlnum__lt=F("gboynum"))
    # Q对象的使用，拿出pk值小于等于14,或者sage大于等于15的学生
    studentList = Students.stuObj1.filter(Q(pk__lte=14) | Q(sage__gt=50))
    # F对象还可以做加减等算术运算
    # gradesList = Grades.objects.filter(ggirlnum__lt=F("gboynum")-50)
    print(studentList)
    # 返回给模板
    return HttpResponse('0000000000')
    # return render(request, "myApp/grades.html", {"grades": gradesList})


# 利用类中定义的方法实现添加学生
def addstudents(request):
    grade = Grades.objects.get(pk=1)
    stu = Students.createStudent("qitiandasheng", 34, True, "wo shi qitiandasheng", grade)
    stu.save()
    return HttpResponse("%s-保存成功" % stu.sname)


# 另外一种方法是利用管理器类中定义的方法实现
def addstudents2(request):
    grade = Grades.objects.get(pk=1)  # get()方法,all()方法就是笔记中所说的过滤器，包括返回多个数据的和返回单个数据的
    stu = Students.stuObj.createStudent("tangseng", 35, True, "wo shi tangseng", grade)
    stu.save()
    return HttpResponse("%s-保存成功" % stu.sname)


def kuabiao(request):
    g = Grades.objects.filter(students__scontend__contains="zhang")
    return render(request, "myApp/grades.html", {"grades": g})


# 测试的时候 url中要带有 ?a=1
def attributions(request):
    print("path:", request.path)
    print("FILES:", request.FILES)
    print(request.GET["a"])  # url中要带有 ?a=1
    print("method:", request.method)
    print("POST:", request.POST)
    print("session:", request.session)
    print("encoding:", request.encoding)
    return HttpResponse("attributions")


# 获取get方法传递的参数
def get1(request):
    print("this is get1 function")
    # a = request.Get.get("a")
    a = request.Get.get("a")
    print(a)
    # # b = request.Get.get("b")
    # b = request.Get["b"]
    # print(b)
    # c = request.Get.get("c")
    # print(c)
    # return HttpResponse(a + " " + b + " " + c)
    return HttpResponse(a)


def get2(request):
    a = request.Get.getlist("a")
    a1 = a[0]
    a2 = a[1]
    return HttpResponse(a1, a2)


def showregist(request):
    return render(request, "myApp/regist.html")


def regist(request):
    name = request.POST.get("name")
    gender = request.POST.get("gender")
    age = request.POST.get("age")
    hobby = request.POST.getlist("hobby")
    print(name)
    print(gender)
    print(age)
    print(hobby)
    return HttpResponse("0000")


def showresponse(request):
    res = HttpResponse()
    res.content = b"sunck is a good man!"
    print(res.content)
    print(res.charset)
    print(res.status_code)
    # print(res.content-type)
    return HttpResponse("0000")


# 测试方法：
# 先把下面两行代码注释掉，演示set_cookie()方法，在响应头中可以看到这个信息
# cookie = request.COOKIES
# res.write("<h1>" + cookie["sunck"] + "</h1>")
# 然后把cookie = res.set_cookie("sunck", "good")注释掉，上述两行放开，演示读取cookie的方法
def cookietest(request):
    res = HttpResponse()
    # cookie = res.set_cookie("sunck", "good") # F12中可以查看到Response响应头中的set-cookie的value是sunck=good

    # 有了上面的设置，以后的请求中cookie都带有此值，以下的语句取出cookie值
    cookie = request.COOKIES
    res.write("<h1>" + cookie["sunck"] + "</h1>")
    return res


def redirect1(request):
    # 如果重定向的url前面没有/，就是在前一个url的基础上在后面直接加重定向的url，
    # return HttpResponseRedirect("redirect2") #就是形成/redirect1/redirect2,会报错

    # 如果加了/，就是写什么url就跳转到该url
    # 此例子是为了从127.0.0.1:80000/sunck/redirct1，跳转到/sunck/redirect2,所以为了正常匹配，下面两个例子应该写成/sunck/redirect2
    # 使用HttpResponseRedirect重定向
    # return HttpResponseRedirect("/sunck/redirect2/")
    # 使用redirect重定向
    return redirect("/sunck/redirect2/")


def redirect2(request):
    return HttpResponse("我是重定向的视图")


def main(request):
    username = request.session.get("name", default="游客")
    print(username)
    return render(request, "myApp/main.html", {"username": username})


def login(request):
    return render(request, "myApp/login.html")


def showmain(request):
    username = request.GET.get("uname")
    request.session["name"] = username
    request.session.set_expiry(10)
    return redirect("/sunck/main")


from django.contrib.auth import logout


def quit(request):
    # logout(request)
    # request.session.clear()
    request.session.flush()
    return redirect("/sunck/main")


# if for 演示，for不能得到学生列表，没做出来，视频在330，问题可能在studentsList = Students.stuObj.all()这句话上
def temp_syntax(request):
    student_1 = Students.stuObj1.get(pk=6)
    return render(request, "myApp/temp_syntax.html", {"stu": student_1, "num": 10})


def template_for(request):
    studentsList = Students.stuObj.all()
    student_1 = Students.stuObj1.get(pk=1)
    # 将数据传递给模板，模板再渲染页面，将渲染 好的页面返回给浏览器
    return render(request, "myApp/students.html", {"students": studentsList, "stu": student_1})


def template_if(request):
    return render(request, "myApp/template_if.html", {"num": 10})


# 网上例子，测试if标签，成功的
def tagtest(request):
    n = 100
    return render(request, "myApp/template_if_2.html", {"num": n})


def tagtest1(request):
    studentsList = Students.stuObj.all()
    print(studentsList)
    return render(request, "myApp/template_filter.html", {"s1": studentsList})


def good(request):
    return render(request, "myApp/good.html", {"num": 10})


def good1(request, ids):
    return render(request, "myApp/good.html", {"num": ids})


def mainpage(request):
    return render(request, "myApp/mainpage.html")


def upfile(request):
    return render(request, "myApp/upfiles.html")


import os
from django.conf import settings


def savefile(request):
    print(request.method)
    if request.method == "post":  # 这里有个问题，upfiles.html虽然指定了post方式，但是获取到的确实get
        f = request.FILES["file"]
        filePath = os.path.join(settings.MEDIA_ROOT, f.name)
        with open(filePath, "wb") as fp:
            for info in f.chunks():
                fp.write(info)
        return HttpResponse("上传成功")

    else:
        return HttpResponse("上传失败")


# 分页功能
from django.core.paginator import Paginator


def studentpage(request, pageid):
    allList = Students.stuObj1.all().order_by("id")
    paginator = Paginator(allList, 10)
    print(paginator.count)
    print(paginator.num_pages)
    print(paginator.page_range)
    page = paginator.page(pageid)
    print(page.has_next())
    print(page.has_previous())
    print(page.previous_page_number())
    print(page.next_page_number())
    # print(page.len())
    # print(page[0])
    return render(request, "myApp/studentpage.html", {"students": page})

# ajax 实验失败，可能是js的引入路径不正确
from django.http import JsonResponse
def ajaxstudent(request):
    print("9999999")
    return render(request, "myApp/ajaxstudent.html")
def studentinfo(request):
    print("0000000")

    stus = Students.stuObj1.all()
    list = []
    for stu in stus:
        list.append([stu.sname, stu.sage])
    return JsonResponse({"data": list})


# 富文本，实验失败
def richtext(request):
    return render(request,"myApp/edit.html")